<template>
	<div class="app-container" v-loading="loading">
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入关键词" clearable
							@keyup.enter="handleQuery" />

					</el-col>
					<el-col :span="6">
						<el-button :loading="loading" type="primary" @click="handleQuery"><template
								#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>
		</div>

		<el-card shadow="never">
			<div class="action-row">
				<el-button v-hasPerm="['engineering.Schedule/read']"  @click="handleDo('', 'act_early')" 
				:disabled="multipleSelection.length !== 1 || !(multipleSelection[0]?.director == useStore.userId || multipleSelection[0]?.qqsx_user == useStore.userId)"
				:type="buttonType(multipleSelection.length)" plain><template
				#icon><i-ep-tickets /></template>前期手续</el-button>
				<el-button v-hasPerm="['engineering.Schedule/read']" @click="handleDo('', 'act_scene')" :disabled="multipleSelection.length !== 1 || !(multipleSelection[0]?.director == useStore.userId || multipleSelection[0]?.xc_user == useStore.userId)"
					:type="buttonType(multipleSelection.length)" plain><template
						#icon><i-ep-operation /></template>现场进度</el-button>
			</div>
			<el-table :key="reload" ref="dataTableRef" v-loading="loading" :data="tableData" align="left"
				tooltip-effect="dark" :show-overflow-tooltip="true" :scrollbar-always-on="true" border
				@cell-mouse-enter="rowMouse" @cell-mouse-leave="menuLineVisible=false"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width"
						:min-width="item.minwidth">
						<template #default="scope" v-if="item.prop == 'name'">
							<span>{{ scope.row.name }}</span>
						</template>
					</el-table-column>
				</template>
			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 新增内容 -->
		<el-dialog v-model="dialogAdd.visible" :close-on-click-modal="false" :close-on-press-escape="false"
			class="elDiaLog" width="1000px" :title="`${dialogAdd.title}`" @close="handleCancle">
			<el-form v-loading="loading3" ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item required label="进度类型">
					<el-tag v-if="queryParams2.type == 1" type="primary"> 前期手续 </el-tag>
					<el-tag v-else type="success"> 现场进度 </el-tag>
				</el-form-item>
				<el-form-item required label="进度说明" prop="content">
					<el-input type="textarea" placeholder="请填写进度说明" resize="none" show-word-limit maxlength="999"
						rows="4" v-model="formData.content" />
				</el-form-item>
				<el-form-item label="图片上传" prop="image">
					<el-upload style="width: 100%;" action="/api/upload" name="file" v-model:file-list="formData.image"
						:show-file-list="true" :multiple="true" :data="{ type: 'images' }" list-type="picture-card"
						:on-preview="onImgPreview" :before-upload="imageBeforUpload" :on-success="(response:any, file:any, fileList:any) => {
							  return imageBeforUploadSuccess(response, file, fileList,'image');
							}">
						<i-ep-plus />
						<template #tip>
							<div class="el-upload__tip">
								<el-text size="small" type="info">文件大小:{{imageType.pageShow}} </el-text>
							</div>
						</template>
					</el-upload>
				</el-form-item>
				<el-form-item label="附件上传" prop="files">
					<el-upload style="width: 100%;" v-model:file-list="formData.files" action="/api/upload" name="file"
						:data="{type: 'file'}" :on-success="(response:any, file:any, fileList:any) => {
                           return imageBeforUploadSuccess(response, file, fileList,'files');
                        }" :on-preview="onFilePreview" :before-upload="imageBeforUpload2" :multiple="true"
						list-type="text">
						<el-button type="primary">上传附件</el-button>
						<template #tip>
							<div class="el-upload__tip">
								<el-text size="small" type="info">文件大小:{{feilType.pageShow}} </el-text>
							</div>
						</template>
					</el-upload>
				</el-form-item>
				<el-form-item label="当前问题" prop="problem">
					<el-input type="textarea" placeholder="请填写当前问题" resize="none" show-word-limit maxlength="999"
						rows="4" v-model="formData.problem" />
				</el-form-item>
				<el-form-item required label="添加时间" prop="add_time">
					<el-date-picker v-model="formData.add_time" type="date" placeholder="请选择添加时间" size="default" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" :loading="loading2" @click="handleSubmit">确定</el-button>
					<el-button @click="handleCancle">取消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 查看表单内容 -->
		<el-drawer v-model="dialogOpen.visible" 
					:title="`${dialogOpen.title}`" 
					direction="rtl" size="80%">
			<div class="action-row">
				<el-button type="primary" v-hasPerm="['engineering.Schedule/save']" @click="handleAdd()" plain>
					<template #icon><i-ep-plus /></template>新增</el-button>	
			</div>
			
			<el-table :data="dataProList" 
					  v-loading="loading2"
					  align="left"
					  tooltip-effect="dark"
					  @selection-change="handleSelectionChange"
					  :show-overflow-tooltip="true" border>
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<el-table-column align="center" label="类型" width="100">
					<template #default="scope">
						<el-tag type="primary" v-if="scope.row.type == 1">前期手续</el-tag>
						<el-tag type="success" v-else>现场</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="进度说明" property="content" align="center" />
				<el-table-column label="当前问题" property="problem" align="center" />
				<el-table-column label="添加时间" property="add_time" align="center" width="150" />
				<el-table-column label="操作人" property="user.name" align="center" width="150" />
				<el-table-column fixed="right" align="center" label="操作" width="200">
					<template #default="scope">
						<el-button  v-hasPerm="['engineering.Schedule/update']"  type="primary" size="small" link @click="handleEdit(scope.row)">
							<template #icon><i-ep-edit /></template>编辑
						</el-button>
						<el-button  v-hasPerm="['engineering.Schedule/delete']"  type="danger" size="small" link @click="handleDelete(scope.row.id)">
							<template #icon><i-ep-delete /></template>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-drawer>

		<el-dialog v-model="ylImg.visible" :close-on-click-modal="false" :close-on-press-escape="false" class="elDiaLog"
			lock-scroll :title="ylImg.info?.name" @close="ylImg.visible = false">
			<div class="prew" style="width: 100%;">
				<img style="width: 100%;display: block;" :src="`${ylImg.info?.url}`" />
			</div>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Schedule",
		inheritAttrs: false,
	});



	import { imageType, feilType, checkFileUploadStatus } from "@/utils/funcall";
	//接口地址
	import {
		addEngineeringSchedule,
		eidtEngineeringSchedule,
		delEngineeringSchedule,
		getEngineeringSchedule,
		getMyengineering
	} from "@/api/engine";
	import { useUserStore } from "@/store/modules/user";
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	const useStore = useUserStore();
	const TableFilter = useTableFilterStore();
	const strtype = ref('engineSche');


	// 表格标题
	const cTitles = ["工程名称", "所属公司", '负责人', '添加时间'];
	// 显示字段
	const sTitles = ["工程名称", "所属公司", '负责人', '添加时间'];
	// 字段属性
	const cColumns = [

		{ label: "工程名称", prop: "name", align: "center", minwidth: 200 },
		{ label: "所属公司", prop: "company.name", align: "center", minwidth: 200 },
		{ label: "负责人", prop: "directorInfo.name", align: "center", minwidth: 150 },
		{ label: "添加时间", prop: "add_time_text", align: "center", minwidth: 150 }
	]

	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}






	const queryFormRef = ref(ElForm);
	const dataFormRef = ref(ElForm)
	const queryParams = reactive({
		page: 1,
		limit: 20,
		name: ""
	})
	const queryParams2 = reactive({
		page: 1,
		limit: 20,
		eid: "",
		type: 1
	})
	const loading = ref(false);
	const loading2 = ref(false);
	const loading3 = ref(false);
	const ids = ref<number[]>([]);
	const total = ref(0);

	var reload = ref();

	const tableData = ref();//首页列表
	const dataProList = ref();//进度列表
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});

	const dialogAdd = reactive<DialogOption>({
		visible: false,
		title: ""
	});
	const dialogOpen = reactive<any>({
		title: "添加信息", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status: "add_art", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value: {}   		  //携带整条参数 row
	});

	const formData : any = ref({
		id: "",
		content: "",
		image: [],
		files: [],
		problem: "",
		add_time: ""
	});
	const rules = reactive({
		content: [{ required: true, message: "请填写进度说明", trigger: "blur" }],
		add_time: [{ required: true, message: "请选择时间", trigger: "blur" }],
	});

	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}

	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	
	// 操作
	function handleDo(row : any, act : string) {
		dialogOpen.status = act
		switch (act) {
			case 'act_early':
				var rowItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				dialogOpen.visible = true;
				dialogOpen.title = '前期手续进度';
				dialogOpen.value = rowItem;
				queryParams2.page = 1;
				queryParams2.limit = 20;
				queryParams2.eid = rowItem.id
				queryParams2.type = 1
				handleProQuery();
				break
			case 'act_scene':
				var rowItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				dialogOpen.visible = true;
				dialogOpen.title = '现场进度';
				dialogOpen.value = rowItem;
				queryParams2.page = 1;
				queryParams2.limit = 20;
				queryParams2.eid = rowItem.id
				queryParams2.type = 2
				handleProQuery();
				break
			default:
		}
	}

	function handleQuery() {
		loading.value = true;
		getMyengineering(queryParams).then((res) => {
			total.value = res.data.count;
			tableData.value = res.data.list;
		}).finally(() => {
			loading.value = false
		})
	}


	function handleAdd() {
		dialogAdd.visible = true;
		dialogAdd.title = '添加信息'
		console.log(formData.value)
		formData.value.id = "";
		formData.value.add_time = new Date().toISOString().slice(0, 10);
		nextTick(() => {

		})
	}
	function handleEdit(el : any) {
		dialogAdd.visible = true;
		dialogAdd.title = '编辑信息'
		nextTick(() => {
			formData.value = Object.assign({}, el);
		})
	}
	function handleDelete(Id ?: number) {
		const Ids = [Id || ids.value].join(",");
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading2.value = true;
			delEngineeringSchedule({
				id: Ids
			}).then((res) => {
				console.log(res)
				ElMessage({
					message: '删除成功',
					type: 'success'
				})
				handleProQuery();
			}).finally(() => {
				loading2.value = false;
			})
		}, function () {
			console.log('取消删除')
		});
	}

	function handleSubmit() {
		let newData = Object.assign({}, formData.value)
		if (!checkFileUploadStatus(newData.image)) {
			ElMessage({
				message: '图片资源正在上传，请稍后提交!',
				type: 'warning',
				duration: 800
			})
			return false;
		}
		if (!checkFileUploadStatus(newData.files)) {
			ElMessage({
				message: '有附件资源正在上传，请稍后提交!',
				type: 'warning',
				duration: 800
			})
			return false;
		}
		loading2.value = true;
		newData.eid = queryParams2.eid
		newData.type = queryParams2.type;
		dataFormRef.value.validate((valid : any, fields : any) => {
			if (valid) {
				if (formData.value.id) {
					eidtEngineeringSchedule(newData).then((res) => {
						ElMessage({
							message: '信息修改成功',
							type: 'success',
						})
						handleCancle()
						handleProQuery();
					}).finally(() => {
						loading2.value = false;
					})
				}
				else {
					addEngineeringSchedule(newData).then((res) => {
						console.log(res)
						ElMessage({
							message: '信息添加成功',
							type: 'success',
						})
						handleCancle()
						handleProQuery();
					}).finally(() => {
						loading2.value = false;
					})
				}
			}
			else {
				loading2.value = false;
			}
		})
	}

	function handleCancle() {
		dataFormRef.value.clearValidate()
		dataFormRef.value.resetFields()
		dialogAdd.visible = false;
		dialogAdd.title = '';
	}

	function handleProQuery() {
		loading2.value = true;
		getEngineeringSchedule(queryParams2).then((res) => {
			dataProList.value = res.data;
		}).finally(() => {
			loading2.value = false
		})
	}

	/**
	 * 文件上传成功 失败则剔除
	 */
	function imageBeforUploadSuccess(response, file, fileList, el) {
		console.log(response, file, fileList, el)
		formData.value[el] = formData.value[el].map(item => {
			if (item.uid == file.uid) {
				const obj : any = {}
				obj.uid = file.uid
				obj.url = response.data.url
				obj.name = file.name
				return obj;
			}
			else {
				return item;
			}
		});
	}



	/**
	* 上传文件 之前的操作
	*/
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < imageType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (imageType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: imageType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: imageType.prompt,
				type: 'error',
			})
			return false;
		}
		console.log('开始上传文件')
	}

	/**
	* 上传文件 之前的操作
	*/
	function imageBeforUpload2(file : any) {
		var fileSize = file.size / 1024 / 1024 < feilType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();

		if (feilType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: feilType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: feilType.prompt,
				type: 'error',
			})
			return false;
		}
	}

	/**
	 * 重置查询
	 */
	function resetQuery() {
		handleQuery();
	}
	// 预览图片
	const ylImg = ref({
		visible: false,
		info: ""
	})
	function onImgPreview(file : any) {
		console.log(file)
		ylImg.value.visible = true;
		ylImg.value.info = file
	}
	// 文件预览 --点击下载
	function onFilePreview(file) {
		if (file.status == "success") {
			const a = document.createElement("a");
			a.href = file.url;
			a.download = file.name.split('.')[0];
			document.body.appendChild(a);
			a.click(); // 点击下载
			document.body.removeChild(a); // 下载完成移除元素
		}
	}

	onMounted(() => {
		handleQuery();
		columnsInit();
	})
</script>
<style lang="scss" scoped>

</style>